package com.example.wac.exception;

import com.example.wac.constant.Constant;
import com.example.wac.vo.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author wuancheng
 * @description 全局异常处理
 * @date 2021-12-30 17:31:00
 */

@RestControllerAdvice(basePackages = "com.example", annotations = Controller.class)
@Slf4j
public class GlobalExceptionHandler {
    private final static Logger error = LoggerFactory.getLogger("error");

    /**
     * 针对统一的业务异常类处理 及特定的shiro异常处理
     */
    @ExceptionHandler({Exception.class})
    public ApiResult exceptionHandler(Exception ex) {
        String errorCode = null;
        String errorDesc = null;
        if (ex instanceof AppException){
           AppException appException = (AppException) ex;
           errorCode = appException.errorCode();
           errorDesc = appException.errorDesc();
        } else if (ex instanceof UnauthenticatedException){
            errorDesc = Constant.Login.USER_UN_AUTHENTICATE;
        } else if (ex instanceof UnauthorizedException){
            errorDesc = Constant.Login.USER_UN_AUTHORIZE;
        }
        error.error(errorDesc,ex);
        return ApiResult.error(errorCode,errorDesc);
    }
}
